package com.ychp.user.dao.redis;

import com.ychp.redis.dao.JedisTemplate;
import com.ychp.user.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

/**
 * Desc:
 * Author: <a href="ychp@terminus.io">应程鹏</a>
 * Date: 16/11/22
 */
@Component
public class UserRedisDao {

    private final static int SESSION_MAX_SECOND = 604800;

    @Autowired
    private JedisTemplate jedisTemplate;

    public Boolean login(final User user, final String token){
        return jedisTemplate.excute(new JedisTemplate.JedisAction<Boolean>() {
            public Boolean action(Jedis jedis) {
                String tmp = jedis.get(sessionKey(user.getId().toString()));
                if(StringUtils.isEmpty(tmp))
                jedis.setex(sessionKey(user.getId().toString()), SESSION_MAX_SECOND, token);
                jedis.setex(sessionKey(token), SESSION_MAX_SECOND, user.getId().toString());
                return true;
            }
        });
    }

    private String sessionKey(String token){
        return "sessions:" + token;
    }
}
